package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.StrategyCatalogQuery;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.vo.CatalogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* 攻略分类服务接口实现
*/
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRepository repsitory;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IStrategyService strategyService;

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        strategyCatalog.setId(null);
        repsitory.save(strategyCatalog);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        repsitory.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public StrategyCatalog get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<StrategyCatalog> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,StrategyCatalog.class, query, pageable);
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        if(StringUtils.hasLength(strategyCatalog.getId())){
            //update
            this.update(strategyCatalog);
        }else{
            //save
            this.save(strategyCatalog);
        }
    }

    @Override
    public List<CatalogVo> queryStrategyCatalog() {
        List<CatalogVo> list = new ArrayList<>();
        // db.strategy_catalog.aggregate([{
        //    $group: {
        //        _id: "$destName",
        //        names: {$push: "$name"},
        //        ids: {$push: "$_id"}
        //    }}])
        // 结果
        // _id              names                       ids
        // 泰国           [第一次去泰国]         [5e3002138c1b00008c00071e]
        // 广州       [长隆度假区,最广州,广式美味]         [ , , ]
        //聚合查询
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
        );
        AggregationResults<Map> result = template.aggregate(agg,Map.class);
        List<Map> datas = result.getMappedResults(); //将结果转化成list<map>   map描述一行数据
        for (Map data : datas) {                    // 遍历这个map {_id:广州,names:[ , ,],ids:[ , , ]},{}...
            CatalogVo catalogVo = new CatalogVo();
            // 查询到目的地的名字       广州
            catalogVo.setDestName(data.get("_id").toString());
            List<Object> names = (List<Object>)data.get("names");       // names:[长隆度假区, 最广州, 广式美味]
            List<Object> ids = (List<Object>)data.get("ids");           // ids:[5e3002138c , 5e3002138c1, 5e3002138c1b]}
            List<StrategyCatalog> catalogList = new ArrayList<>();
            for (int i = 0; i < names.size(); i++) {
                StrategyCatalog sc = new StrategyCatalog();
                sc.setName(names.get(i).toString());                // 长隆度假区
                sc.setId(ids.get(i).toString());                    // 5e3002138c
                catalogList.add(sc);
            }
            catalogVo.setCatalogList(catalogList);
            list.add(catalogVo);
        }
        return list;
    }

    @Override
    public List<StrategyCatalog> queryCatalogListByDestId(String destId) {
        // 通过 目的地 id 查询到 攻略分类集合
        List<StrategyCatalog> catalogList = repsitory.findByDestId(destId);
        // 遍历集合，得到一个个 攻略分类对象
        for (StrategyCatalog catalog : catalogList) {
            // 通过 攻略分类id，查询到 攻略明细集合
            List<Strategy> strategies = strategyService.queryByCatalogId(catalog.getId());
            // 设置到当前 攻略分类对象的 strategies 属性
            catalog.setStrategies(strategies);
        }
        return catalogList;
    }
}
